<template>
  <v-container fluid class="pa-0">
    <v-row>
      <v-col cols="12">
        <div class="mx-auto" style="max-width: 1200px;">
          <!-- Search Field -->
          <v-card flat class="pa-6 rounded-lg">
            <v-text-field
              v-model="searchValue"
              :loading="isSearching"
              density="comfortable"
              variant="outlined"
              prepend-inner-icon="mdi-magnify"
              label="输入关键词搜索"
              hide-details
              clearable
              @keyup.enter="handleSearch"
              @click:prepend-inner="handleSearch"
              @click:clear="handleClearSearch"
            >
              <template #append>
                <v-fade-transition hide-on-leave>
                  <v-btn
                    v-if="searchValue"
                    color="primary"
                    @click="handleSearch"
                  >
                    搜索
                  </v-btn>
                </v-fade-transition>
              </template>
            </v-text-field>
          </v-card>

          <!-- Tabs Section -->
          <v-card flat class="mt-4 pa-4">
            <v-slide-y-transition>
              <btn-tabs
                v-model:modelValue="activeTab"
                :tabs="classification"
                :is-all="true"
                @change="handleTabChange"
              />
            </v-slide-y-transition>
          </v-card>

          <!-- Content Section -->
          <v-card flat class="mt-4 pa-4">
            <div class="content-container">
              <!-- Loading State -->
              <v-fade-transition mode="out-in">
                <div
                  v-if="isLoading"
                  class="content-layout"
                >
                  <v-skeleton-loader
                    v-for="index in 6"
                    :key="index"
                    type="card"
                    width="360"
                    height="210"
                    :loading="true"
                    class="skeleton-card"
                  />
                </div>
                <div v-else class="content-layout">
                  <card-list
                    v-if="materials.length"
                    :list="materials"
                    :loading="isLoading"
                    class="fade-enter-active"
                  />
                </div>
              </v-fade-transition>
            </div>

            <!-- Error Message -->
            <v-snackbar
              v-model="showError"
              color="error"
              :timeout="3000"
              location="top"
            >
              {{ errorMessage }}
            </v-snackbar>
          </v-card>

          <!-- Pagination -->
          <v-card flat class="mt-4 d-flex justify-center pa-4">
            <v-fade-transition>
              <v-pagination
                v-if="totalPages > 1"
                v-model="currentPage"
                :length="totalPages"
                :disabled="isLoading"
                :total-visible="5"
                density="comfortable"
                rounded="circle"
                active-color="black"
                color="grey-darken-3"
                @update:model-value="handlePageChange"
              />
            </v-fade-transition>
          </v-card>
        </div>
      </v-col>
    </v-row>
  </v-container>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { getMaterialList } from '@/api/material'
import { useAppStore } from '@/stores/app'
import { useRoute } from 'vue-router'
import { debounce } from 'lodash-es'

definePage({
  name: 'categoryList'
})

const route = useRoute()
const appStore = useAppStore()

// Reactive references
const searchValue = ref('')
const currentPage = ref(1)
const activeTab = ref('0')
const materials = ref([])
const totalPages = ref(0)
const rootKey = ref(undefined)
const isLoading = ref(false)
const classification = ref([])

// Additional reactive references
const isSearching = ref(false)
const showError = ref(false)
const errorMessage = ref('')
const limit = ref(6)

// 优化 fetchMaterialList，添加延迟以改善过渡效果
const fetchMaterialList = async () => {
  if (isLoading.value) return

  isLoading.value = true
  try {
    // 添加小延迟以确保动画平滑
    await new Promise(resolve => setTimeout(resolve, 100))
    const response = await getMaterialList({
      offset: limit.value * (currentPage.value - 1),
      name: searchValue.value?.trim() || undefined,
      limit: limit.value,
      second_category_id: activeTab.value !== '0' ? [Number(activeTab.value)] : undefined,
      first_category_id: rootKey.value
    })

    // 添加小延迟以确保加载动画完整显示
    await new Promise(resolve => setTimeout(resolve, 200))

    totalPages.value = Math.ceil(response.count / limit.value)
    materials.value = response.data
  } catch (error) {
    console.error('Failed to fetch materials:', error)
    materials.value = []
    totalPages.value = 0
    showError.value = true
    errorMessage.value = '数据加载失败，请稍后重试'
  } finally {
    isLoading.value = false
    isSearching.value = false
  }
}

// Enhanced search handler
const handleSearch = debounce(() => {
  if (!searchValue.value.trim()) return
  isSearching.value = true
  currentPage.value = 1
  fetchMaterialList()
}, 300)

const handleClearSearch = () => {
  searchValue.value = ''
  currentPage.value = 1
  fetchMaterialList()
}

// Enhanced page change handler
const handlePageChange = () => {
  window.scrollTo({ top: 0, behavior: 'smooth' })
  fetchMaterialList()
}

// Tab change handler
const handleTabChange = () => {
  currentPage.value = 1
  fetchMaterialList()
}

// Optimized watchers
watch([searchValue, activeTab, currentPage, rootKey], () => {
  if (activeTab.value && rootKey.value) {
    fetchMaterialList()
  }
}, { deep: true })

watch(
  () => route.query.categoryId,
  (newCategoryId) => {
    if (!newCategoryId || !appStore.materialCategory.length) return

    const selectedCategory = appStore.materialCategory.find(
      (item) => item.id == newCategoryId
    )

    if (route.query.q) {
      searchValue.value = route.query.q
    }

    if (selectedCategory) {
      appStore.activeMaterialCategory = newCategoryId
      classification.value = selectedCategory.second_categories || []
      rootKey.value = newCategoryId
      activeTab.value = Number(route.query.id) || '0'
      currentPage.value = 1
    }
  },
  { immediate: true }
)

watch(
  () => route.query.id,
  (newId) => {
    if (newId) {
      activeTab.value = Number(newId)
    }
  }
)

// Optimized mounted lifecycle hook
onMounted(async () => {
  try {
    await appStore.getMaterialCategory()
    const categoryId = route.query.categoryId

    if (categoryId) {
      console.log('category id:', categoryId);

      const selectedCategory = appStore.materialCategory.find(
        (item) => item.id == categoryId
      )
      if (selectedCategory) {
        appStore.activeMaterialCategory = categoryId
        classification.value = selectedCategory.second_categories || []
        rootKey.value = categoryId
        activeTab.value = Number(route.query.id) || '0'
      }
    } else if (appStore.materialCategory.length > 0) {
      const defaultCategory = appStore.materialCategory[0]
      classification.value = defaultCategory.second_categories || []
      rootKey.value = defaultCategory.id
    }

    await fetchMaterialList()
  } catch (error) {
    console.error('Failed to initialize category list:', error)
  }
})
</script>

<style scoped>
.v-pagination {
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  border-radius: 30px;
  padding: 4px;
}

.skeleton-card {
  opacity: 0.7;
  transition: opacity 0.3s ease;
}

.content-container {
  position: relative;
  min-height: 590px;
  overflow: hidden;
}

.content-layout {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  min-height: 590px;
  width: 100%;
}

.fade-enter-active {
  animation: fadeIn 0.3s ease-out;
}

.v-fade-transition-enter-active,
.v-fade-transition-leave-active {
  transition: opacity 0.3s ease;
}

.v-fade-transition-enter-from,
.v-fade-transition-leave-to {
  opacity: 0;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

:deep(.v-btn) {
  &.v-btn--active {
    background-color: black !important;
    color: white !important;
  }

  &:hover {
    background-color: rgba(0, 0, 0, 0.1) !important;
  }
}

:deep(.v-skeleton-loader) {
  background-color: rgba(0, 0, 0, 0.05) !important;
}
</style>
